package cso.loadso;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import cso.loadso.databinding.ActivityMainBinding;


/**
 * GOOS=android
 * GOARCH=arm
 * CGO_ENABLED=1
 * # CC=$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/windows-x86_64/bin/armv7a-linux-androideabi21-clang
 * CC=$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/windows-x86_64/bin/aarch64-linux-android21-clang
 * <p>
 * echo $ANDROID_NDK_HOME
 * <p>
 * GOOS=android GOARCH=arm CGO_ENABLED=1 CC=$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/windows-x86_64/bin/armv7a-linux-androideabi22-clang go build -ldflags "-s -w" -buildmode=c-shared -o libadd.so lib.go
 * #GOOS=android GOARCH=arm64 CGO_ENABLED=1 CC=$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/windows-x86_64/bin/aarch64-linux-android21-clang go build -ldflags "-s -w" -buildmode=c-shared -o libadd.so lib.go
 */


public class MainActivity extends AppCompatActivity {
    String TAG = "cc";

    // Used to load the 'loadso' library on application startup.
    static {
        System.loadLibrary("loadso");
    }

    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());


        // 检查是否已授予存储权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            // 权限未授予，请求权限
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.INTERNET}, 2000);
        } else {
            // 权限已授予，执行需要存储权限的操作
            Log.d(TAG, "存储权限已授予");
        }

        String filesDirPath = getFilesDir().getAbsolutePath();

        String fileURI = "http://192.168.88.11:9780/client/app/libadd.so";
        downloadAndSaveSoFile(fileURI, filesDirPath + "/libadd.so");

        Button button = findViewById(R.id.my_btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取文件目录路径
                // getExternalFilesDir(Environment.DIRECTORY_PICTURES);

                Log.d(TAG, "onCreate1: " + filesDirPath);
                Log.d(TAG, "readSize " + readSize);

                File directory = new File(filesDirPath);
                File[] files = directory.listFiles();
                if (files != null) {
                    Log.d(TAG, "onCreate: " + files.length);
                    for (File file : files) {
                        if (file.isFile()) {
                            Log.d(TAG, ">>>>> " + file.getName());
                        }
                    }
                }

                String helloValue = helloSo(filesDirPath);
                Log.d(TAG, "onCreate2: " + helloValue);

                // helloValue = stringFromJNI();

                // Example of a call to a native method
                TextView tv = binding.sampleText;
                tv.setText(helloValue);
            }
        });


    }

    /**
     * A native method that is implemented by the 'loadso' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    public native String helloSo(String fileDirPath);


    int readSize = 0;

    public void downloadAndSaveSoFile(String fileUrl, String fileName) {

        Toast.makeText(this, "connect...", Toast.LENGTH_LONG).show();

        Thread thread = new Thread(() -> {

            try {
                // 创建URL对象
                URL url = new URL(fileUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                int code = connection.getResponseCode();
                if (code == HttpURLConnection.HTTP_OK) {
                    runOnUiThread(() -> {
                        Toast.makeText(this, "connect success", Toast.LENGTH_SHORT).show();
                    });
                    try (InputStream in = connection.getInputStream(); FileOutputStream out = new FileOutputStream(fileName)) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = in.read(buffer)) != -1) {
                            readSize += bytesRead;
                            Log.d(TAG, String.format("downloadAndSaveSoFile: %d %d", bytesRead, readSize));
                            out.write(buffer, 0, bytesRead);
                        }
                    }

                    runOnUiThread(() -> {
                        Toast.makeText(this, String.format("download size %d", readSize), Toast.LENGTH_LONG).show();
                    });
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(this, String.format("connect fail. %d", code), Toast.LENGTH_LONG).show();
                    });
                }
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    Toast.makeText(this, String.format("connect exception. %s", e.getMessage()), Toast.LENGTH_LONG).show();
                });
            }
        });
        thread.start();
    }
}